package com.example.musicplayer.profile.settings

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.util.Log
import android.widget.Button
import android.widget.EditText
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.bumptech.glide.Glide
import com.example.musicplayer.R
import com.example.musicplayer.dao.UserProfileDAO
import com.example.musicplayer.model.UserProfile
import com.karumi.dexter.Dexter
import com.karumi.dexter.MultiplePermissionsReport
import com.karumi.dexter.PermissionToken
import com.karumi.dexter.listener.multi.MultiplePermissionsListener
import java.io.ByteArrayOutputStream
import java.io.InputStream

class EditProfileActivity : AppCompatActivity() {

    private lateinit var profileImage: ImageView
    private lateinit var usernameEditText: EditText
    private lateinit var bioEditText: EditText
    private lateinit var phoneEditText: EditText
    private lateinit var genderEditText: EditText
    private lateinit var birthdayEditText: EditText
    private lateinit var locationEditText: EditText
    private lateinit var schoolEditText: EditText
    private lateinit var saveButton: Button
    private lateinit var chooseImageButton: Button
    private lateinit var backButton: ImageButton
    private var imageUri: Uri? = null

    private lateinit var userProfileDAO: UserProfileDAO
    private var userId: Int = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_edit_profile)

        profileImage = findViewById(R.id.profile_image)
        usernameEditText = findViewById(R.id.username_edit_text)
        bioEditText = findViewById(R.id.bio_edit_text)
        phoneEditText = findViewById(R.id.phone_edit_text)
        genderEditText = findViewById(R.id.gender_edit_text)
        birthdayEditText = findViewById(R.id.birthday_edit_text)
        locationEditText = findViewById(R.id.location_edit_text)
        schoolEditText = findViewById(R.id.school_edit_text)
        saveButton = findViewById(R.id.save_button)
        chooseImageButton = findViewById(R.id.choose_image_button)
        backButton = findViewById(R.id.ibBack)

        userProfileDAO = UserProfileDAO(this)

        // 从 Intent 中获取用户 ID
        userId = intent.getIntExtra("user_id", 0)

        // 请求存储权限
        requestStoragePermissions()

        // 加载用户信息
        loadUserProfile()

        chooseImageButton.setOnClickListener {
            selectImage()
        }

        saveButton.setOnClickListener {
            saveUserProfile()
        }

        // 添加返回按钮的点击事件
        backButton.setOnClickListener {
            finish()
        }
    }

    private fun requestStoragePermissions() {
        Dexter.withContext(this)
            .withPermissions(
                Manifest.permission.READ_EXTERNAL_STORAGE
            )
            .withListener(object : MultiplePermissionsListener {
                override fun onPermissionsChecked(report: MultiplePermissionsReport) {
                    if (report.areAllPermissionsGranted()) {
                        // 权限已授予
                    } else {
                        // 用户拒绝了某些权限
                        showPermissionDeniedDialog()
                    }
                }

                override fun onPermissionRationaleShouldBeShown(
                    permissions: List<com.karumi.dexter.listener.PermissionRequest>,
                    token: PermissionToken
                ) {
                    token.continuePermissionRequest()
                }
            })
            .onSameThread()
            .check()
    }

    private fun selectImage() {
        val intent = Intent(Intent.ACTION_GET_CONTENT)
        intent.type = "image/*"
        startActivityForResult(intent, 1)
    }

    @Deprecated("Deprecated in Java")
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 1 && resultCode == Activity.RESULT_OK && data != null) {
            imageUri = data.data
            try {
                val inputStream: InputStream? = contentResolver.openInputStream(imageUri!!)
                val bitmap = BitmapFactory.decodeStream(inputStream)
                profileImage.setImageBitmap(bitmap)
            } catch (e: Exception) {
                e.printStackTrace()
                Toast.makeText(this, "加载图片失败", Toast.LENGTH_SHORT).show()
            }
        }
    }

    private fun saveUserProfile() {
        val username = usernameEditText.text.toString()
        val bio = bioEditText.text.toString()
        val phone = phoneEditText.text.toString()
        val gender = genderEditText.text.toString()
        val birthday = birthdayEditText.text.toString()
        val location = locationEditText.text.toString()
        val school = schoolEditText.text.toString()
        val imageBytes: ByteArray? = imageUri?.let { uriToByteArray(it) }

        val userProfile = UserProfile(
            id = userId,
            username = username,
            bio = bio,
            phone = phone,
            gender = gender,
            birthday = birthday,
            location = location,
            school = school,
            image = imageBytes,
            password = null // 不传递密码
        )

        if (userProfileDAO.getUserProfile(userId) == null) {
            userProfileDAO.insertUserProfile(userProfile)
        } else {
            userProfileDAO.updateUserProfile(userProfile)
        }

        Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show()
    }

    private fun uriToByteArray(uri: Uri): ByteArray? {
        val inputStream: InputStream? = contentResolver.openInputStream(uri)
        val byteArrayOutputStream = ByteArrayOutputStream()
        val buffer = ByteArray(1024)
        var read: Int

        try {
            while (inputStream?.read(buffer).also { read = it!! } != -1) {
                byteArrayOutputStream.write(buffer, 0, read)
            }
            inputStream?.close()
            return byteArrayOutputStream.toByteArray()
        } catch (e: Exception) {
            e.printStackTrace()
            Log.e("EditProfileActivity", "转换图片失败: ${e.message}")
        }

        return null
    }

    private fun loadUserProfile() {
        val userProfile = userProfileDAO.getUserProfileById(userId)
        if (userProfile != null) {
            Log.d("EditProfileActivity", "User Profile loaded: $userProfile")
            usernameEditText.setText(userProfile.username)
            bioEditText.setText(userProfile.bio)
            phoneEditText.setText(userProfile.phone)
            genderEditText.setText(userProfile.gender)
            birthdayEditText.setText(userProfile.birthday)
            locationEditText.setText(userProfile.location)
            schoolEditText.setText(userProfile.school)

            userProfile.image?.let {
                val bitmap = BitmapFactory.decodeByteArray(it, 0, it.size)
                profileImage.setImageBitmap(bitmap)
            }
        } else {
            Log.e("EditProfileActivity", "User Profile not found for user ID: $userId")
        }
    }

    private fun showPermissionDeniedDialog() {
        // 显示一个对话框，提示用户需要授权
        Toast.makeText(this, "需要存储权限才能选择图片", Toast.LENGTH_SHORT).show()
    }
}